<template>
  <div class="change-email-container">
    <div class="change-email-content">
      <el-card class="email-card">
        <el-breadcrumb
          separator-class="el-icon-arrow-right"
          style="margin: 20px 0px 30px 0px"
        >
          <el-breadcrumb-item
            :to="{ path: '/accountInformation/account-setting' }"
            >账号设置</el-breadcrumb-item
          >
          <el-breadcrumb-item>修改邮箱</el-breadcrumb-item>
        </el-breadcrumb>
        <el-form
          :model="emailForm"
          label-width="120px"
          class="email-change-form"
          label-position="left"
          :rules="emailFormRules"
          ref="emailForm"
        >
          <el-row>
            <el-col :span="18" :offset="1">
              <el-form-item label="请输入新邮箱" prop="newEmail">
                <el-input
                  v-model.trim="emailForm.newEmail"
                  spellcheck="false"
                  placeholder="请输入新邮箱"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="14" :offset="1">
              <el-form-item label="请填写验证码" prop="verificationCode">
                <el-input
                  v-model.trim="emailForm.verificationCode"
                  spellcheck="false"
                  placeholder="请输入验证码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <!-- 发送验证码和显示倒计时的组件是交替显示的 -->
              <el-button
                v-show="!countDownShow"
                plain
                type="primary"
                @click="sendVerificationCode"
                icon="el-icon-message"
                >发送验证码</el-button
              >
              <el-button
                plain
                type="primary"
                v-show="countDownShow"
                @click="noticeUserInfo"
              >
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ countDownTime }}
                &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" :offset="7">
              <el-button
                type="primary"
                @click="submitEmailForm('emailForm')"
                icon="el-icon-edit"
                >修改邮箱</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { sendVerificationCode, changeUserEmail } from "@/apis/apis";
@Component({
  name: "changeEmail",
})
export default class changeEmail extends Vue {
  emailForm: {
    newEmail: string;
    verificationCode: string;
  } = {
    newEmail: "",
    verificationCode: "",
  };
  // 表单校验规则
  emailFormRules = {
    newEmail: [
      { required: true, message: "请输入新邮箱", trigger: "blur" },
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: "blur",
      },
    ],
    verificationCode: [
      { required: true, message: "请输入验证码", trigger: "blur" },
    ],
  };
  // 定时器的设置
  countDownShow: boolean = false;
  countDownTime: number = 60;
  countDownTimer: any = null;
  // 发送验证码
  sendVerificationCode() {
    // 必须要校验邮箱格式正确后才能发送验证码
    // 邮箱检验格式
    const emailRegex = new RegExp(
      "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
    );
    if (!emailRegex.test(this.emailForm.newEmail)) {
      this.$message.error("请输入正确的邮箱地址");
      return;
    }
    // 开启定时器
    this.startCountDown();
    sendVerificationCode(this.emailForm.newEmail)
      .then((res) => {
        // console.log(res);
        if (res.data.code === "200") {
          this.$message.success("验证码发送成功");
        } else {
          this.$message.error("验证码发送失败，请稍后重试");
          // 发送失败时重置定时器
          this.resetCountDown();
        }
      })
      .catch((err) => {
        console.log(err);
        this.resetCountDown();
        console.log("this is error from sendVerificationCode");
      });
  }
  // 表单校验后提交
  submitEmailForm(formName: string) {
    (this.$refs[formName] as any).validate((valid: boolean) => {
      if (valid) {
        changeUserEmail(
          this.emailForm.newEmail,
          this.emailForm.verificationCode
        )
          .then((res) => {
            // console.log(res);
            if (res.data.code === "200") {
              this.$message.success("修改邮箱成功!");
              // 修改成功后重置定时器
              this.resetCountDown();
            } else {
              this.$message.error("修改邮箱失败!");
              console.log("submitEmailForm error");
            }
          })
          .catch((err) => {
            console.log(err);
            console.log("this is error from submitEmailForm");
          });
      } else {
        console.log("submitEmailForm error");
        this.$message.error("请检查输入是否正确");
        return false;
      }
    });
  }
  // 定时器开始计时
  startCountDown() {
    // 开始显示定时器
    this.countDownShow = true;
    this.countDownTimer = setInterval(() => {
      if (this.countDownTime > 0) {
        this.countDownTime--;
      } else {
        this.resetCountDown();
      }
    }, 1000);
  }
  // 重置定时器
  resetCountDown() {
    clearInterval(this.countDownTimer);
    this.countDownShow = false;
    this.countDownTime = 60;
  }
  // 用户操作的提示信息系
  noticeUserInfo() {
    this.$message.warning("请在" + this.countDownTime + "秒后再次发送验证码");
  }
  // 在组件销毁时重置定时器
  beforeDestroy() {
    this.resetCountDown();
  }
}
</script>

<style lang="scss" scoped>
.change-email-container {
  .change-email-content {
    .email-card {
      width: 100%;
      height: 480px;
    }
  }
}
</style>